package com.yuan.statemachine.core;

import com.yuan.statemachine.core.AbstractStateMachine;
import com.yuan.statemachine.core.StateMachine;
import com.yuan.statemachine.core.StateMachineRegistry;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author wjwei
 */
public class BindStateMachine implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof AbstractStateMachine) {
            StateMachine stateMachine = applicationContext.getBean(StateMachineRegistry.class);
            ((AbstractStateMachine<?, ?, ?>) bean).registrar(stateMachine);
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
